package model;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Database management class, used to provide database access to Data Access Objects
 * 
 * @author INTI3D
 *
 */
public class DBmanager {
	
	private static DBmanager uniqueInstance=null;
	
	private Connection con = null ;
	private File dbdir = new File("WebFarmDB");
	private final String driver = "org.apache.derby.jdbc.EmbeddedDriver" ;
	private final String dbname =  "jdbc:derby:C:/Documents and Settings/Administrator/WebfarmDB";
	
	 
        
	/**
	 * Check if the db exists or not
	 */
	private DBmanager() {
		System.out.println(dbdir.getAbsolutePath());
		if (!dbExists(dbname)) {
			System.err.println("database not found....");			
		}
	}

	/**
	 * Makes the DBmanager a singleton
	 * @return the DBmanager
	 */
	public static synchronized DBmanager getInstance() {
		if (uniqueInstance==null) {
			uniqueInstance = new DBmanager();
		}
		return uniqueInstance;
	}
	
	/**
	 * A method to check if the db exists
	 * @param dataSource the location of the db
	 * @return True or false if the db exists
	 */
	private Boolean dbExists(String dataSource) {
		Boolean exists = false ;
		try{
			Class.forName(driver) ;
            con = DriverManager.getConnection(dataSource);
           
			exists = true ;
		} catch(Exception e){
			; // Do nothing, as DB does not (yet) exist
		}
		return(exists) ;
	}

	/**
	 * Closes the connection with the DB
	 */
	public void close() {
		try {
			con = DriverManager.getConnection(dbname + ";shutdown=true");
		}catch(SQLException se) {
			; // Do Nothing. System has shut down.
		con = null ;
		}
	}
	
	/**
	 * Returns the connection
	 * @return the Connection
	 */
	public Connection getConnection() {
		return con;
	}
}
